type FetchType = typeof $fetch
export type FetchOptions = Parameters<FetchType>[1]

export function useClientRequest<T = unknown>(url: string, opts?: FetchOptions, meta?: any) {
  const userPinia = useUserPinia()
  const token = userPinia.getToken
  const runtimeConfig = useRuntimeConfig()
  const nuxtApp = useNuxtApp()

  const defaultOptions: FetchOptions = {
    onRequest({ options }) {
      options.method = opts.method.toString()
      if (url.indexOf('http') !== 0)
        options.baseURL = opts?.baseURL?.toString() || runtimeConfig.public.api.baseUrl
      options.headers = new Headers(options.headers)
      options.headers.set('Client', 'front_web')
      // 添加请求头,没登录不携带token
      const isToken = meta?.isToken || false
      if (isToken)
        options.headers.set('Authorization', `Bearer ${token}`)
      options.params = paramsSerializer(opts.params)
    },
  }
  const fetch = $fetch<T>(url, { ...defaultOptions, ...opts }) as any
  // 实际请求
  return fetch.then((res) => {
    console.log(res,'sssss')
    switch (res.code) {
      case 401:
        // TODO 登录过期
        userPinia.setToken('')
        nuxtApp.runWithContext(() => navigateTo('/login'))
        break
      case 500:
        handleError(res.msg)
        break
    }
    if (res.code !== 200000) {
      console.log('🚀 ~ file: useServerRequest.ts:35 ~ defaultOptions ~ url:', { url })
      console.log('🚀 ~ file: useServerRequest.ts:36 ~ defaultOptions ~ context:', res)
      return Promise.reject(res)
    }
    return { ...res }
  })
}
